define(function(require, exports, module){
	/**
	 * @class LazyLoad
	 * @memberof Nuui
	 * @classdesc 图片延迟加载, 仅对在显示区域内的图片进行加载<br/>
	 * 		延迟加载的图片标签的书写格式:<br/>
	 * 		1, 添加lazy类<br/>
	 *		2, 添加属性data-original, 值为所加载的图片路径<br/>
	 *		3, 延迟加载图片的src值是预置图<br/>
	 *		示范: `<img src='placeHoledImage.jpg' class='lazy' data-original='./img/01.jpg'/>`<br/>
	 *		注意点:<br/>
	 *		1, container须有滚动属性;<br/>
	 *		2, 延迟加载的图片须设近似所加载图片高度的min-height;<br/>
	 * @param {object} configs - 配置
	 * @param {string} configs.container - 图片浏览滚动的容器的css选择器字符串<br/>
	 * @param {number} configs.threshold - 图片露出多少比例才加载的系数, 默认值是0.5 <br/>
	 * @example var imgLoader = new LazyLoad({
	 * 		container: '#imgContainer',
	 * 		threshold: 0.3
	 * 	});
	 */
	var LazyLoad = module.exports = function(configs){

		this.configs = $.extend({}, this._defaultConfigs, configs);
		
		this.initialize();

		return this;
	};

	LazyLoad.prototype = {
		_staticConfigs:{
			eventType: 'scroll.LazyLoad',
			data_attribute: "original",
			lazyImgClass: 'lazy'
		},
		
		_defaultConfigs: {
			container: window,
			threshold: 0.5,
			triggerFreq: 4
		},

		_scrollCount: 0,

		_scrollTopMemory: 0,

		initialize: function(){
			this._$container = $(this.configs.container);

			this._$container.on(this._staticConfigs.eventType, $.proxy(this._onScroll, this));

			this._$container.trigger(this._staticConfigs.eventType);
		},

		_getLazyLoadImgs: function(){
			return this._$container.find('img.' + this._staticConfigs.lazyImgClass);
		},

		/*
		* 滚动容器触发的检测加载图片方法
		* */
		_onScroll: function(){
			if(this._scrollCount++ % this._defaultConfigs.triggerFreq != 0){
				return;
			}

			var scrollTop = this._$container.scrollTop();

			if(scrollTop - this._scrollTopMemory > 30 || scrollTop == 0){
				this._scrollTopMemory = scrollTop;

				var $imgs = this._getLazyLoadImgs(),
					len = $imgs.length;

				if(!len)return;

				for(var i = 0; i < len; i++){

					var img = $imgs[i];

					if(this._verticalVisible(img, scrollTop)){
						this._loadImg(img);
					} else {
						break; // 当遍历到不在可视范围内的, 便停止遍历
					}
				}
			}
		},

		/*
		* 加载图片方法
		* */
		_loadImg: function(item){
			var $item = $(item).removeClass(this._staticConfigs.lazyImgClass),
				imgSrc = $item.attr("data-" + this._staticConfigs.data_attribute);

			function onLoad() {
				$item
					.animate({ opacity: 0 }, 100, function() {
						$item
							.attr('src', imgSrc)// 更新图片
							.animate({ opacity: 1 }, 500, function() {
								//callback
							});
					});
			}

			$("<img />")
				.bind("load", onLoad)
				.attr("src", imgSrc);
		},

		/*
		* 计算img对应的可视范围, 即加载范围
		* */
		_imgVisionHeight: function(img, scrollTop){
			return scrollTop + this._$container[0].clientHeight - img.height * this.configs.threshold;
		},

		_verticalVisible: function(img, scrollTop){
			return img.offsetTop < this._imgVisionHeight(img, scrollTop)
		}
	};
});